package main

import (
	"context"
	"fmt"
)

func main() {
	//func WithValue(parent Context, key, val interface{}) Context

	//WithValue returns a copy of parent in which the value associated with key is val.
	//
	//Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.
	//
	//The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context.
	//Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.

	//WithValue 返回父的副本，其中与键关联的值为 val。
	//
	//仅将上下文值用于传输进程和 API 的请求范围的数据，而不用于将可选参数传递给函数。
	//
	//提供的键必须是可比较的，并且不应是字符串类型或任何其他内置类型，以避免使用上下文的包之间发生冲突。
	//WithValue 的用户应该定义他们自己的键类型。 为了避免在分配给接口时进行分配{}，上下文键通常具有具体的类型 struct{}。
	//或者，导出的上下文键变量的静态类型应该是指针或接口。

	ctx := context.WithValue(context.Background(), "test", "go")
	f(ctx, "test")
	f(ctx, "test1")
	//found value: go
	//key not found test1
}

func f(ctx context.Context, k string) {
	if v := ctx.Value(k); v != nil {
		fmt.Println("found value:", v)
		return
	}
	fmt.Println("key not found", k)
}
